from odoo import api ,fields, models, _


class ProductTemplate(models.Model):
    _name = 'product.template'
    _inherit = ['product.template', 's.mes.upload']

    @api.model_create_multi
    def create(self, vals_list):
        res = super().create(vals_list)
        if self.s_check_allow():
            for r in res:
                r.wms_post_async()
        return res

    def wms_cron_all(self):
        """初次对接批量同步物料"""
        records = self.sudo().search([('id', '>', 0)])
        for r in records:
            r.wms_post_async()

    def wms_post_async(self):
        """WMS只需要原材料基础数据"""
        infos = []
        vals = {"reqTime": fields.Datetime.to_string(fields.Datetime.now()), 'matInfos': []}
        if self.detailed_type == 'product' and self.categ_id and self.categ_id.code != 'CHP':
            infos.append({
                'MaterialID': self.default_code,
                'MaterialName': self.name,
                'Spec': self.standards if self.standards else '',
                'EarlyWarn': self.categ_id.s_expiration_time, # 预警天数
                'Class': self.categ_id.name,
                'Unit': self.uom_id.name,
                'PurchasingUnitName': self.uom_po_id.name if self.uom_po_id else None,
                'ConversionRatio': self.uom_po_id.factor_inv if self.uom_po_id else 1
            })
        if infos:
            vals['matInfos'] = infos
            self.wms_upload_data(vals, '/JehaitWS/JOVETG/MaterialData')
